import { ListItem } from '../ui/panel/type'
import { getRootDocument } from './dom'

const getItemByDom = (el: HTMLElement): ListItem => {
  if(!el) return
  const id = el.id
  const done = $('.done_icon_show', el).length > 0
  const current = $(el).hasClass('s_pointerct')
  const name = $('.s_pointti', el).text()
  const type = $(el).attr('itemtype')
  return { id, done, name, type, current }
}

export const getPlayList = (): ListItem[] => {
  const EL_SELECTOR = '.s_sectionwrap>[itemtype]'
  const list: ListItem[] = []
  $(EL_SELECTOR, getRootDocument()).map((i, el) => {
    list.push(getItemByDom(el))
  })
  return list
}

export const getCurrent = () => {
  const list = getPlayList()
  return list.find(i => i.current)
}

export const getDomById = (id: string) => {
  return $(`#${id}`, getRootDocument())
}

export const playNext = ( current = getCurrent()) => {
  const getSureNext = (id: string) => {
    const list = getPlayList()
    const listOmitDone = list.filter(t => !t.done || t.id === current.id)
    const index = listOmitDone.findIndex(i => i.id === id)
    return listOmitDone?.[index+1]
  }
  const next = getSureNext(current.id)
  if(!next) return

  getDomById(next.id)?.trigger('click')
}
